{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 霍夫变换"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 基本概念\n",
    "霍夫变换是一种特征提取技术，主要应用于检测图像中的直线或者圆。\n",
    "OpenCV 中分为霍夫线变换和霍夫圆变换。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 霍夫线变换\n",
    "##### 分类\n",
    "- 标准霍夫变换（SHT）      cv2.HoughLines\n",
    "- 多尺度霍夫变换 （MSHT）   cv2.HoughLines\n",
    "- 累计概率霍夫变换 （PPHT）  cv2.HoughLinesP\n",
    "\n",
    "**注意：在使用霍夫线变换之前，首先要对图像进行边缘检测的处理，即霍夫线变换的直接输入只能是边缘二值图像**\n",
    "\n",
    "##### 标准霍夫变换\n",
    "使用极坐标来表示直线，对于在笛卡尔坐标上直线上所有给定的点，在极坐标上都能转换成正弦曲线，直线上所有点绘制出来的正弦曲线交与一点，若交于交点的曲线数量超过一定阈值，说明在笛卡尔坐标上表示一条直线。 [更多资料] (https://blog.csdn.net/ycj9090900/article/details/52944708)\n",
    "\n",
    "`HoughLines(image, rho, theta, threshold[, lines[, srn[, stn[, min_theta[, max_theta]]]]]) -> lines`\n",
    "- image: 输入图像，需为 8 位的单通道二进制图像\n",
    "- rho: 以像素为单位的距离精度\n",
    "- theta: 以弧度为单位的角度精度\n",
    "- threshold: 阈值参数\n",
    "- srn: 默认值为 0 对于多尺度霍夫变换，srn 表示进步尺寸 rho 的除数距离，粗略的累加器进步尺寸直接是 rho ，而精确的累加器进步尺寸为 rho/srn。\n",
    "- stn: 默认值为 0 对于多尺度霍夫变换，stn 表示进步尺寸的单位角度 theta 的除数距离。若 srn stn 同时为 0，表示使用经典的霍夫变换，否则这两个参数都应该是正数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-27T06:28:16.125336Z",
     "start_time": "2019-02-27T06:28:12.682327Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/HoughLines.jpg\")\n",
    "edges = cv2.Canny(img, 50, 200, apertureSize=3)\n",
    "gray = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)\n",
    "\n",
    "# 经典的霍夫变换\n",
    "lines = cv2.HoughLines(edges, 1, np.pi/180, 180, 0, 0) # 在图像中找到的所有直线都存储在这里\n",
    "for i in range(lines.shape[0]-1):\n",
    "    rho, theta = lines[i][0][0], lines[i][0][1] # rho 为距离， theta 为角度，把每条直线的参数分离出来\n",
    "    \n",
    "    # 坐标转换\n",
    "    a = np.cos(theta)\n",
    "    b = np.sin(theta)\n",
    "    x0 = a*rho\n",
    "    y0 = b*rho\n",
    "    x1 = int(x0 + 1000*(-b))\n",
    "    y1 = int(y0 + 1000*(a))\n",
    "    x2 = int(x0 - 1000*(-b))\n",
    "    y2 = int(y0 - 1000*(a))\n",
    "    # 绘制直线\n",
    "    cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 255), 2)\n",
    "    \n",
    "cv2.imshow(\"img\", img)    \n",
    "cv2.imshow(\"gray\", gray)\n",
    "cv2.imshow(\"edges\", edges)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0k60d0zv5j211r0hp4be.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[图像卷积与滤波的一些知识点] (https://blog.csdn.net/zouxy09/article/details/49080029)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 注意，下面的坐标变换不是很清楚"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-27T03:27:15.079772Z",
     "start_time": "2019-02-27T03:26:50.929504Z"
    }
   },
   "outputs": [],
   "source": [
    "img = np.zeros((200, 200, 3), dtype=np.uint8)\n",
    "cv2.line(img, (0, 100), (100, 0), (0, 255, 0), 2)\n",
    "cv2.line(img, (0, 150), (150, 0), (0, 255, 0), 2)\n",
    "edges = cv2.Canny(img, 50, 200, apertureSize=3)\n",
    "gray = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)\n",
    "\n",
    "# 经典的霍夫变换\n",
    "lines = cv2.HoughLines(edges, 1, np.pi/180, 100, 0, 0) # 在图像中找到的所有直线都存储在这里\n",
    "\n",
    "for i in range(lines.shape[0]-1):\n",
    "    rho, theta = lines[i][0][0], lines[i][0][1] # rho 为距离， theta 为角度，把每条直线的参数分离出来\n",
    "    \n",
    "    # 坐标转换\n",
    "    a = np.cos(theta)\n",
    "    b = np.sin(theta)\n",
    "    x0 = a*rho\n",
    "    y0 = b*rho\n",
    "    x1 = int(x0 + 1000*(-b))\n",
    "    y1 = int(y0 + 1000*(a))\n",
    "    x2 = int(x0 - 1000*(-b))\n",
    "    y2 = int(y0 - 1000*(a))\n",
    "    # 绘制直线\n",
    "    cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 255), 2)\n",
    "    \n",
    "cv2.imshow(\"img\", img)    \n",
    "cv2.imshow(\"gray\", gray)\n",
    "cv2.imshow(\"edges\", edges)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ktjawzxxj20gt06k0su.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 累计概率霍夫变换\n",
    "累计概率霍夫变换可以找出图像中直线大概的起始和终止坐标，返回 4 个元素，分别代表起始坐标（x1, y1）,终止坐标（x2, y2）\n",
    "\n",
    "`HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) -> lines`\n",
    "- image: 输入图像，需为 8 位单通道二进制图像\n",
    "- rho: 以像素为单位的距离精度，另一种表述方式是：直线搜索时的进步尺寸的单位半径\n",
    "- theta: 以弧度为单位的角度精度，另一种表述方式是：直线搜索时的进步尺寸的单位角度\n",
    "- threshold: 阈值参数\n",
    "- lines: 存储检测到的线条的输出矢量，返回 4 个元素，分别代表起始坐标（x1, y1）,终止坐标（x2, y2）\n",
    "- minLineLength: 默认值 0 表示最低线段的长度，比这个设定参数短的线段不能显示出来\n",
    "- maxLineGap: 默认值 0 允许将同一行点与点之间连接起来的最大的距离。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-27T08:32:59.632310Z",
     "start_time": "2019-02-27T08:32:55.335771Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/HoughLines.jpg\")\n",
    "edges = cv2.Canny(img, 50, 200, apertureSize=3) # 边缘检测出来就是二值图像\n",
    "gray = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)\n",
    "\n",
    "threshold = 80\n",
    "minLineLength = 40\n",
    "maxLineGap = 10\n",
    "linesP = cv2.HoughLinesP(edges, 1, np.pi/180, threshold, minLineLength, maxLineGap)\n",
    "\n",
    "for i in range(linesP.shape[0]):\n",
    "    x1 = linesP[i][0][0]\n",
    "    y1 = linesP[i][0][1]\n",
    "\n",
    "    x2 = linesP[i][0][2]\n",
    "    y2 = linesP[i][0][3]\n",
    "    cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 255), 2)\n",
    "\n",
    "cv2.imshow(\"img\", img)    \n",
    "cv2.imshow(\"gray\", gray)\n",
    "cv2.imshow(\"edges\", edges)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0kto6pa62j20cz0hs3zn.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-27T06:25:24.491618Z",
     "start_time": "2019-02-27T06:25:17.328721Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "def nothing(x):\n",
    "    pass\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/HoughLines.jpg\")\n",
    "edges = cv2.Canny(img, 50, 200, apertureSize=3) # 边缘检测出来就是二值图像\n",
    "\n",
    "cv2.namedWindow(\"gray\")\n",
    "cv2.createTrackbar(\"minLineLength\", \"gray\", 0, 200, nothing)\n",
    "cv2.createTrackbar(\"maxLineGap\", \"gray\", 0, 200, nothing)\n",
    "\n",
    "\n",
    "while(1):\n",
    "    \n",
    "    gray = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)\n",
    "    minLineLength = cv2.getTrackbarPos(\"minLineLength\", \"gray\")\n",
    "    maxLineGap = cv2.getTrackbarPos(\"maxLineGap\", \"gray\")\n",
    "    linesP = cv2.HoughLinesP(edges, 1, np.pi/180, 70, minLineLength, maxLineGap)\n",
    "    for i in range(linesP.shape[0]):\n",
    "        x1 = linesP[i][0][0]\n",
    "        y1 = linesP[i][0][1]\n",
    "\n",
    "        x2 = linesP[i][0][2]\n",
    "        y2 = linesP[i][0][3]\n",
    "        cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 255), 2)\n",
    "    k = cv2.waitKey(1) & 0xff\n",
    "    if k == 27:\n",
    "        break\n",
    "    #cv2.imshow(\"img\", img)    \n",
    "    cv2.imshow(\"gray\", gray)\n",
    "    #cv2.imshow(\"edges\", edges)\n",
    "\n",
    "\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0kyomq8j4j20cz0k60tp.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 霍夫圆变换\n",
    "\n",
    "##### 原理\n",
    "圆的表达式为 $(x-a)^{2} + (y-b)^{2} = r^{2}$ ，将圆上的任意点 (x, y) 变换成 (a, b, r) 坐标结果是一个圆锥，同一个圆上的点形成的圆锥会交于一点，从该交点可以得出圆的信息。\n",
    "\n",
    "\n",
    "\n",
    "`HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) -> circles`\n",
    "- image:输入图像，需为 8 位单通道二进制图像\n",
    "- method: 使用的检测方法，目前只有 `cv2.HOUGH_GRADIENT` 霍夫梯度法一种\n",
    "- dp: 用来检测圆心的累加器图像的分辨率于输入图像之比的倒数，且此参数允许创建一个比输入图像分辨率低的累加器。例如，如果dp= 1时，累加器和输入图像具有相同的分辨率。如果dp=2，累加器便有输入图像一半那么大的宽度和高度。\n",
    "- minDist:**为霍夫变换检测到的圆的圆心之间的最小距离**，即让我们的算法能明显区分的两个不同圆之间的最小距离。这个参数如果太小的话，多个相邻的圆可能被错误地检测成了一个重合的圆。反之，这个参数设置太大的话，某些圆就不能被检测出来了。\n",
    "- param1: 有默认值100。它是参数method设置的检测方法的对应的参数。对当前唯一的方法霍夫梯度法CV_HOUGH_GRADIENT，它表示传递给canny边缘检测算子的高阈值，而低阈值为高阈值的一半。\n",
    "- param2: 有默认值100。它是参数method设置的检测方法的对应的参数。对当前唯一的方法霍夫梯度法CV_HOUGH_GRADIENT，它表示在检测阶段圆心的累加器阈值。它越小的话，就可以检测到更多根本不存在的圆，而它越大的话，能通过检测的圆就更加接近完美的圆形了。\n",
    "- minRadius: int类型的minRadius,有默认值0，表示圆半径的最小值。\n",
    "- maxRadius: int类型的maxRadius,也有默认值0，表示圆半径的最大值。\n",
    "- circles: 返回的结果，包含三个元素 (x, y, radius)，圆心和半径\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 图片例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-28T06:56:55.294467Z",
     "start_time": "2019-02-28T06:56:51.939407Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "\"\"\"\n",
    "img = np.zeros((200, 200, 3), dtype=np.uint8)\n",
    "cv2.circle(img, (100, 100), 50, (0, 255, 255))\n",
    "cv2.circle(img, (95, 100), 50, (0, 255, 255))\n",
    "cv2.circle(img, (80, 100), 50, (0, 255, 255))\n",
    "\"\"\"\n",
    "\n",
    "img = cv2.imread(\"./sample_img/opencv-logo.png\")\n",
    "img1 = cv2.imread(\"./sample_img/opencv-logo.png\", 0)\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "gaussian = cv2.GaussianBlur(gray, (9, 9), 2, 2)\n",
    "circle = cv2.HoughCircles(gaussian, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=50, minRadius=0, maxRadius=0)\n",
    "\n",
    "for i in range(circle.shape[1]):\n",
    "    center = (circle[0][i][0], circle[0][i][1])\n",
    "    radius = circle[0][i][2]\n",
    "    cv2.circle(img, center, radius, (100, 100, 100), 4)\n",
    "    cv2.circle(img, center, 3, (100, 100, 100))\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"img1\", cv2.Canny(img1, 50, 200, apertureSize=3))\n",
    "cv2.imshow(\"gray\", gray)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0l263ehq2j20h50lcdgf.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 视频例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-04T13:28:17.551391Z",
     "start_time": "2019-03-04T13:27:50.322799Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "# 设置摄像头分辨率\n",
    "cap.set(cv2.CAP_PROP_FRAME_WIDTH, 400)\n",
    "cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 400)\n",
    "while(1):\n",
    "    # 提取每一帧, frame 源视频\n",
    "    _, frame = cap.read()\n",
    "    frame = cv2.flip(frame, 1)\n",
    "    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n",
    "    #gaussian = cv2.GaussianBlur(gray, (9, 9), 2, 2)\n",
    "    #canny = cv2.Canny(gaussian, 20, 100)\n",
    "    circle = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1,\n",
    "                              minDist=20, param1=50, param2=50, minRadius=0, maxRadius=0)\n",
    "\n",
    "    if circle is not None:\n",
    "        center = (circle[0][0][0], circle[0][0][1])\n",
    "        radius = circle[0][0][2]\n",
    "        cv2.circle(frame, center, radius, (0, 0, 255), 4)\n",
    "\n",
    "    cv2.imshow(\"frame\", frame)  # 源视频\n",
    "    #cv2.imshow(\"gray\", gray) # 源视频\n",
    "\n",
    "    k = cv2.waitKey(1) & 0xFF\n",
    "    if k == 27:\n",
    "        break\n",
    "\n",
    "cap.release()  # 记得释放掉捕获的视频\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0m6ielzm9j20a9094q75.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 效果并不是很好，是由于霍夫变换存在一定缺陷"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多资料\n",
    "[霍夫圆变换原理] (https://blog.csdn.net/yuwuzhi1989/article/details/18614727)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-28T07:14:22.574303Z",
     "start_time": "2019-02-28T07:14:22.568308Z"
    }
   },
   "source": [
    "### 重映射\n",
    "#### 基本概念\n",
    "重映射：把一副图像中某位置的像素放置到另一个图片指定位置的过程，为了完成映射过程，需要获得一些插值为非整数像素的坐标，因为原图像和目标图像的像素坐标是不一一对应的。\n",
    "\n",
    "`remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue]]]) -> dst`\n",
    "- src: 源图像\n",
    "- map1: 1.表示点 (x, y) 的第一个映射  2.表示 CV_16SC2、CV_32FC1、或 CV_32FC2 类型的 X 值\n",
    "- map2: 根据 map1 参数来确定表示的对象，1. 若 map1 表示点 (x, y) 时，该参数不代表任何值  2. 表示 CV_16UC1、CV_32FC1 类型的 Y 值\n",
    "- interpolation: 插值的参数，在原图找不到的坐标使用插值补全\n",
    "- borderMode: 边界模式\n",
    "- borderValue: "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T06:47:58.956515Z",
     "start_time": "2019-03-01T06:47:53.160835Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "def remap_mode(mode, map_x, map_y):\n",
    "    if mode == 0:   # 倒置\n",
    "        for i in range(map_x.shape[0]):\n",
    "            map_x[i,:] = [x for x in range(map_x.shape[1])]\n",
    "        for j in range(map_y.shape[1]):\n",
    "            #map_y[:,j] = [map_y.shape[0]-y for y in range(map_y.shape[0])]  \n",
    "            map_y[:,j] = [map_y.shape[0]-y-1 for y in range(map_y.shape[0])]  \n",
    "    elif mode == 1: # 竖直对称\n",
    "        for i in range(map_x.shape[0]):\n",
    "            map_x[i,:] = [map_x.shape[1]-x for x in range(map_x.shape[1])]\n",
    "        for j in range(map_y.shape[1]):\n",
    "            map_y[:,j] = [y for y in range(map_y.shape[0])]        \n",
    "    elif mode == 2: # mode=0 和 mode=1 的组合\n",
    "        for i in range(map_x.shape[0]):\n",
    "            map_x[i,:] = [map_x.shape[1]-x for x in range(map_x.shape[1])]\n",
    "        for j in range(map_y.shape[1]):\n",
    "            map_y[:,j] = [map_y.shape[0]-y for y in range(map_y.shape[0])]\n",
    "    elif mode == 3: # 缩小后在中间显示\n",
    "        for i in range(map_x.shape[0]):\n",
    "            for j in range(map_x.shape[1]):\n",
    "                if j > map_x.shape[1]*0.25 and j < map_x.shape[1]*0.75 and i > map_x.shape[0]*0.25 and i < map_x.shape[0]*0.75:\n",
    "                    map_x[i,j] = 2 * (j-map_x.shape[1]*0.25) + 0.5\n",
    "                    map_y[i,j] = 2 * (i-map_y.shape[0]*0.25) + 0.5\n",
    "                else:\n",
    "                    map_x[i,j] = 0\n",
    "                    map_y[i,j] = 0\n",
    "                    \n",
    "                    \n",
    "#img = cv2.imread(\"./sample_img/apple.jpg\")\n",
    "img = cv2.imread(\"./sample_img/Back_Projection_Theory2.jpg\", 0)\n",
    "\n",
    "# 创建两个映射矩阵 x, y \n",
    "map_x = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32)\n",
    "map_y = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32)\n",
    "cv2.imshow(\"img\", img)\n",
    "for i in range(4):\n",
    "    remap_mode(i, map_x, map_y)\n",
    "    dst = cv2.remap(img, map_x, map_y, cv2.INTER_LINEAR)    \n",
    "    cv2.imshow(\"dst\"+str(i), dst)\n",
    "    #print(map_x, map_y, map_x.shape, map_y.shape)\n",
    "    \n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-02-28T11:43:25.170577Z",
     "start_time": "2019-02-28T11:43:25.057611Z"
    }
   },
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0me1jtu5yj20r80jme48.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 部分参数解释（以倒置为例）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T07:06:35.462688Z",
     "start_time": "2019-03-01T07:06:35.447699Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]\n",
      " [0. 1. 2. 3. 4.]]\n",
      "[[3. 3. 3. 3. 3.]\n",
      " [2. 2. 2. 2. 2.]\n",
      " [1. 1. 1. 1. 1.]\n",
      " [0. 0. 0. 0. 0.]]\n",
      "[[10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]\n",
      " [25 26 27 28 29]]\n",
      "[[25 26 27 28 29]\n",
      " [20 21 22 23 24]\n",
      " [15 16 17 18 19]\n",
      " [10 11 12 13 14]]\n"
     ]
    }
   ],
   "source": [
    "img = np.array(np.arange(10, 30).reshape(4, 5), dtype=np.uint8)\n",
    "map1 = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32)\n",
    "map2 = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32)\n",
    "\n",
    "\n",
    "# 倒置\n",
    "for i in range(map1.shape[0]):\n",
    "    map1[i,:] = [x for x in range(map1.shape[1])] # 行坐标\n",
    "for j in range(map2.shape[1]):\n",
    "    map2[:,j] = [map2.shape[0]-y-1 for y in range(map2.shape[0])]  # 列坐标\n",
    "\n",
    "    \n",
    "print(map1, map2, sep='\\n')    \n",
    "print(img, cv2.remap(img, map1, map2, cv2.INTER_LINEAR), sep='\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`cv2.remap()` 函数中的 map1, map2 参数代表目标图中的 (x,y) 点在原图中的 x 坐标（由map2提供）与 y 坐标（由map1提供）**待定** \n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0mhqxtwznj20a205ndfu.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 与 cv2.flip() 函数比较\n",
    "`flip(src, flipCode[, dst]) -> dst`\n",
    "- src: 源图像\n",
    "- flipCode: 变换代码\n",
    "    - 0: 倒影\n",
    "    - 1: 左右镜面\n",
    "    - 2: 0+1 的效果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T07:27:18.645345Z",
     "start_time": "2019-03-01T07:27:17.740864Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/apple.jpg\")\n",
    "flip = cv2.flip(img, 0)\n",
    "flip_2 = cv2.flip(img, 1)\n",
    "flip_3 = cv2.flip(img, -1)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"flip\", flip)\n",
    "cv2.imshow(\"flip_2\", flip_2)\n",
    "cv2.imshow(\"flip_3\", flip_3)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T07:22:15.586884Z",
     "start_time": "2019-03-01T07:22:15.579888Z"
    }
   },
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0nbo3ddn8j210h0a24kq.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 直方图\n",
    "#### 直方图基本概念，分析\n",
    "学习目标：\n",
    "- OpenCV 和 Numpy 中的函数查找直方图\n",
    "- 绘制直方图\n",
    "- cv2.calcHist(), np.histogram(), plt.hist()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "直方图就是灰色图像每个像素，横坐标代表像素值（0 - 255），纵坐标代表每个像素值的个数。直方图可以直观了解该图像的对比度，亮度，强度分布。\n",
    "类似：![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0nk57qjnej207i0860tg.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### OpenCV 中的直方图计算函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) -> hist`\n",
    "- images: uint8 或者 float32 类型的图像， 使用时格式为 [img]\n",
    "- channels: 通道标识，若图像为灰度图，则使用 [0]，彩色图用 [0], [1], [2] 分别代表蓝绿红通道的直方图\n",
    "- mask: 掩模，抽取图像中的某块区域时使用，创建的掩模白底就是目标区域，否则为黑色，mask 大小需与原图一致\n",
    "- histSize: 量程，代表直方图横坐标的最大值，对于图像来说使用 [256]\n",
    "- range: 像素值的范围 [0, 256]\n",
    "- hist: 返回一个序列，代表每个像素值的数量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T07:44:23.462640Z",
     "start_time": "2019-03-06T07:44:23.377690Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "img = cv2.imread(\"./sample_img/apple.jpg\")\n",
    "hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "hue = np.zeros(hsv.shape, dtype=np.uint8)\n",
    "hue = cv2.mixChannels(hsv, hue, [0, 0])\n",
    "hist = cv2.calcHist(hue, [0], None, [180], [0, 180]) # 返回的是 (0, 256) 每个像素值的个数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Numpy 中的直方图计算函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T13:20:21.745959Z",
     "start_time": "2019-03-01T13:20:21.732964Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "hist, bins = np.histogram(img.ravel(), 256, [0, 256])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T13:21:54.410796Z",
     "start_time": "2019-03-01T13:21:54.402800Z"
    }
   },
   "outputs": [],
   "source": [
    "hist = np.bincount(img.ravel(), minlength=256) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 对于一维直方图，使用 np.bincount() 的速度比 np.histogram() 快 10 倍，但是 OpenCV 的方法更快，所以还是使用 OpenCV 的直方图方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 直方图的绘制"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`plt.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)`\n",
    "- x: 序列或者数组，大小为 (n, )\n",
    "- bins: 在直方图中（像素值），代表将 256 等分的分数\n",
    "- range: 像素值的范围，例如 (0, 256)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-01T13:25:41.749824Z",
     "start_time": "2019-03-01T13:25:40.887285Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "img = cv2.imread(\"./sample_img/apple.jpg\", 0)\n",
    "plt.hist(img.ravel(), 256, [0, 256])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0o6fefqfoj20b606e0ss.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T01:14:18.895059Z",
     "start_time": "2019-03-02T01:14:16.091664Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = cv2.imread('./sample_img/apple.jpg')\n",
    "\n",
    "color = ('b', 'g', 'r')\n",
    "for i, col in enumerate(color):\n",
    "    histr = cv2.calcHist([img], [i], None, [256], [0, 256])\n",
    "    plt.plot(histr, color=col)\n",
    "    plt.xlim([0, 256]) # 横坐标限制在 0 - 256\n",
    "plt.show()\n",
    "\n",
    "cv2.imshow(\"img\", img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0o6fw85yfj20ad06cq3b.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 添加掩模"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T01:31:06.054138Z",
     "start_time": "2019-03-02T01:31:05.565420Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread('./sample_img/apple.jpg', 0)\n",
    "\n",
    "# create a mask\n",
    "mask = np.zeros(img.shape[:2], np.uint8)\n",
    "mask[100:300, 100:400] = 255\n",
    "masked_img = cv2.bitwise_and(img, img, mask=mask)\n",
    "\n",
    "# Calculate histogram with mask and without mask\n",
    "# Check third argument for mask\n",
    "hist_full = cv2.calcHist([img], [0], None, [256], [0, 256])\n",
    "hist_mask = cv2.calcHist([img], [0], mask, [256], [0, 256])\n",
    "\n",
    "plt.subplot(221), plt.imshow(img, 'gray')\n",
    "plt.subplot(222), plt.imshow(mask, 'gray')\n",
    "plt.subplot(223), plt.imshow(masked_img, 'gray')\n",
    "plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)\n",
    "plt.xlim([0, 256])\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T01:25:32.317504Z",
     "start_time": "2019-03-02T01:25:32.310510Z"
    }
   },
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0oe3ynr32j209d06iaam.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 直方图均衡化\n",
    "直方图均衡化被用来改善图像的**对比度**\n",
    "\n",
    "直方图均衡化简单来说，就是把原始图像的直方图的分布均匀到所有像素。\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ofe737dyj208c03rmx2.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 均衡化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T06:05:45.193628Z",
     "start_time": "2019-03-02T06:05:07.457483Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/Histograms.jpg\")\n",
    "\n",
    "\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "histograms = cv2.equalizeHist(gray)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"histograms\", histograms)\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对图像的灰度图像进行直方图均衡化\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0oez77yymj210m0j9hdt.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T06:06:24.761369Z",
     "start_time": "2019-03-02T06:06:10.596510Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/Histograms.jpg\")\n",
    "blue, green, red = cv2.split(img)\n",
    "\n",
    "blue_histograms = cv2.equalizeHist(blue)\n",
    "green_histograms = cv2.equalizeHist(green)\n",
    "red_histograms = cv2.equalizeHist(red)\n",
    "new_img = cv2.merge((blue_histograms, green_histograms, red_histograms))\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"new_img\", new_img)\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对图像是 BGR 三通道进行直方图均衡化\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0oezucrmaj210s0j8x6p.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T06:08:05.640772Z",
     "start_time": "2019-03-02T06:07:56.917527Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/Histograms.jpg\")\n",
    "hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)\n",
    "h, l, s = cv2.split(img)\n",
    "\n",
    "#h = cv2.equalizeHist(h)\n",
    "l = cv2.equalizeHist(l)\n",
    "#s = cv2.equalizeHist(s)\n",
    "new_img = cv2.merge((h, s, v))\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"new_img\", new_img)\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对图像的 HLS 三通道的 L（亮度） 通道进行直方图均衡化\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0of1m4yd8j210s0jbhdt.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T06:30:19.363784Z",
     "start_time": "2019-03-02T06:30:19.011986Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = cv2.imread('./sample_img/wiki.jpg', 0)\n",
    "\n",
    "hist, bins = np.histogram(img.flatten(), 256, [0, 256])\n",
    "\n",
    "cdf = hist.cumsum() # 返回一个给定轴上的元素的累积和\n",
    "cdf_normalized = cdf * hist.max() / cdf.max()\n",
    "\n",
    "plt.plot(cdf_normalized, color='b')\n",
    "plt.hist(img.flatten(), 256, [0, 256], color='r')\n",
    "\n",
    "plt.xlim([0, 256])\n",
    "plt.legend(('cdf', 'histogram'), loc='upper left')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ofnb0y8zj20he0c3weq.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T06:41:55.020887Z",
     "start_time": "2019-03-02T06:41:51.155974Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = cv2.imread('./sample_img/wiki.jpg', 0)\n",
    "\n",
    "equ = cv2.equalizeHist(img)\n",
    "\n",
    "new_img = np.hstack((img, equ))\n",
    "\n",
    "cv2.imshow(\"new_img\", new_img)\n",
    "#cv2.imwrite(\"./sample_img/equalizeHist.jpg\", new_img)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0og1befzvj211y0cqas4.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### CLAHE (Contrast Limited Adaptive Histogram Equalization) 自适应均衡化\n",
    "以上图像的均衡化使用的是全局的对比度，但有时候全局的对比度不一定是最好的，故引申出自适应均衡化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T06:54:16.690877Z",
     "start_time": "2019-03-02T06:54:12.058455Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "img = cv2.imread('./sample_img/tsukuba_l.png',0)\n",
    "histograms = cv2.equalizeHist(img)\n",
    "\n",
    "hstack_img = np.hstack((img, histograms))\n",
    "cv2.imshow(\"hstack_img\", hstack_img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ogdjluzyj20lt094agm.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 直方图均衡后背景对比度有所提高。但比较两个图像中的雕像的脸。由于亮度过高，我们丢失了大部分信息。这是因为它的直方图并不局限于特定区域。\n",
    "\n",
    "自适应均衡化的原理是：图像被分成称为“tile”的小块（在OpenCV中，tileSize 默认为 8x8）。然后像往常一样对这些块中的每一个进行直方图均衡。所以在一个小区域内，直方图会限制在一个小区域（除非有噪音）。如果有噪音，它会被放大。为避免这种情况，应用对比度限制。如果任何直方图区间高于指定的对比度限制（在 OpenCV 中默认为 40 ），则在应用直方图均衡之前，将这些像素剪切并均匀分布到其他区间。均衡后，为了去除图块边框中的瑕疵，应用双线性插值。\n",
    "\n",
    "`cv2.createCLAHE([, clipLimit[, tileGridSize]]) -> retval`\n",
    "- clipLimit: 用于对比度限制的阈值\n",
    "- tileGridSize: 用于直方图均衡化的网格大小。输入图像将被分割成大小相等的矩形块。tileGridSize 定义行和列中的块的数量。\n",
    "\n",
    "`apply(src, [, dst]) -> dst`  :利用对比度有限的自适应直方图均衡化来均衡灰度图像的直方图。\n",
    "- src: CV_8UC1 类型的图像\n",
    "- dst: 输出的图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T07:07:04.922406Z",
     "start_time": "2019-03-02T07:07:00.124164Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "\n",
    "img = cv2.imread('./sample_img/tsukuba_l.png', 0)\n",
    "\n",
    "# create a CLAHE object (Arguments are optional).\n",
    "clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n",
    "cl1 = clahe.apply(img)\n",
    "\n",
    "cv2.imshow('clahe_2', cl1)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ogqz4z6bj20b5094adj.jpg)\n",
    "\n",
    "雕像区域的轮廓变得清晰可见了"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 如何调整图像的对比度（附加的）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 136,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-02T07:33:55.962340Z",
     "start_time": "2019-03-02T07:33:36.643874Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"./sample_img/brain.jpg\", 0)\n",
    "hist = cv2.equalizeHist(img)  # 直方图均衡\n",
    "\n",
    "threshold = img.copy()\n",
    "threshold[threshold > 127] = 255\n",
    "threshold[threshold <= 127] = 0\n",
    "\n",
    "clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n",
    "cl1 = clahe.apply(img)\n",
    "\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.imshow(\"hist\", hist)\n",
    "cv2.imshow(\"threshold\", threshold)\n",
    "cv2.imshow(\"cl1\", cl1)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ohi5wmmwj20la0esqb4.jpg)\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0ohitn1p7j20lg0esdkz.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2D 直方图\n",
    "以上绘制的是一维直方图（只考虑一个特征，即灰度强度值），本节将讨论 2D 直方图，考虑两个特征（色调和饱和度），用于查找颜色直方图。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T06:58:57.732063Z",
     "start_time": "2019-03-06T06:58:55.644257Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = cv2.imread(\"./sample_img/home.jpg\")\n",
    "hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "# OpenCV 方法\n",
    "# [0, 1] 代表 H 和 S 平面\n",
    "# [190, 256] 180 是 H 平面最大幅值，256 是 S 平面最大幅值\n",
    "hist_cv = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])\n",
    "\n",
    "# Numpy 方法\n",
    "hist_numpy, xbins, ybins = np.histogram2d(hsv[0].ravel(), hsv[1].ravel(),\n",
    "                                    [180, 256], [[0, 180], [0, 256]])\n",
    "\n",
    "cv2.imshow(\"original\", img)\n",
    "cv2.imshow(\"hist_cv\", hist_cv)\n",
    "cv2.imshow(\"hist_numpy\", hist_numpy)\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T07:01:16.407585Z",
     "start_time": "2019-03-06T07:01:16.064784Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "plt.imshow(hist_cv, interpolation=\"nearest\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g1dqakywbpj209k06m0st.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T07:01:21.807479Z",
     "start_time": "2019-03-06T07:01:21.462679Z"
    }
   },
   "outputs": [],
   "source": [
    "plt.imshow(hist_numpy, interpolation=\"nearest\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g1dqazqdibj209x06jjrc.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0pufytcmhj20sv0bhk0s.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-03T12:08:49.894903Z",
     "start_time": "2019-03-03T12:08:49.535565Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "img = cv2.imread('./sample_img/home.jpg')\n",
    "hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "hist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])\n",
    "\n",
    "plt.imshow(hist, interpolation='nearest')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39gy1g0pueqwcfwj20a106l3yl.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 直方图比较"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-24T03:33:49.948388Z",
     "start_time": "2019-03-24T03:33:49.860439Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "base_img = cv2.imread(\"./sample_img/comparehist (1).jpg\")\n",
    "half_base = base_img[0:base_img.shape[0]//2, 0:base_img.shape[1]//2]\n",
    "test_img = cv2.imread(\"./sample_img/comparehist (2).jpg\")\n",
    "test2_img = cv2.imread(\"./sample_img/comparehist (3).jpg\")\n",
    "\n",
    "\n",
    "base_hsv = cv2.cvtColor(base_img, cv2.COLOR_BGR2HSV)\n",
    "half_hsv = cv2.cvtColor(half_base, cv2.COLOR_BGR2HSV)\n",
    "test_hsv = cv2.cvtColor(test_img, cv2.COLOR_BGR2HSV)\n",
    "test2_hsv = cv2.cvtColor(test2_img, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "\n",
    "base_hist = cv2.calcHist([base_hsv], [0, 1], None, [\n",
    "                         180, 256], [0, 180, 0, 256])\n",
    "half_hist = cv2.calcHist([half_hsv], [0, 1], None, [\n",
    "                         180, 256], [0, 180, 0, 256])\n",
    "test_hist = cv2.calcHist([test_hsv], [0, 1], None, [\n",
    "                         180, 256], [0, 180, 0, 256])\n",
    "test2_hist = cv2.calcHist([test2_hsv], [0, 1], None, [\n",
    "                          180, 256], [0, 180, 0, 256])\n",
    "\n",
    "base_hist = cv2.normalize(base_hist, base_hist, 0, 1, cv2.NORM_MINMAX, -1)\n",
    "half_hist = cv2.normalize(half_hist, half_hist, 0, 1, cv2.NORM_MINMAX, -1)\n",
    "test_hist = cv2.normalize(test_hist, test_hist, 0, 1, cv2.NORM_MINMAX, -1)\n",
    "test2_hist = cv2.normalize(test2_hist, test2_hist, 0, 1, cv2.NORM_MINMAX, -1)\n",
    "\n",
    "methods = ['cv2.HISTCMP_CORREL', 'cv2.HISTCMP_CHISQR', 'cv2.HISTCMP_INTERSECT',\n",
    "           'cv2.HISTCMP_BHATTACHARYYA', 'cv2.HISTCMP_HELLINGER', 'cv2.HISTCMP_CHISQR_ALT', 'cv2.HISTCMP_KL_DIV']\n",
    "for i in range(5):\n",
    "    base_base = cv2.compareHist(base_hist, base_hist, i)\n",
    "    half_base = cv2.compareHist(base_hist, half_hist, i)\n",
    "    base_test = cv2.compareHist(base_hist, test_hist, i)\n",
    "    base_test2 = cv2.compareHist(base_hist, test2_hist, i)\n",
    "    print(\"method:\"+str(methods[i]), sep='\\n')\n",
    "    print(\"base_base:\", base_base, \"half_base\", half_base,\n",
    "          \"base_test\",  base_test, \"base_test2\", base_test2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 结果\n",
    "- method:cv2.HISTCMP_CORREL base_base: 1.0 half_base 0.868398994704612 base_test 0.08065514950383738 base_test2 0.05901126222644142\n",
    "- method:cv2.HISTCMP_CHISQR base_base: 0.0 half_base 21.246470173301855 base_test 53204.28067584426 base_test2 1583.6240597344906\n",
    "- method:cv2.HISTCMP_INTERSECT base_base: 37.25639865006087 half_base 14.123541084351018 base_test 17.150308343523648 base_test2 9.475103021075483\n",
    "- method:cv2.HISTCMP_BHATTACHARYYA base_base: 0.0 half_base 0.47332301423304435 base_test 0.7157340757283192 base_test2 0.6902075908999336\n",
    "- method:cv2.HISTCMP_HELLINGER base_base: 0.0 half_base 38.69455570916867 base_test 697.8930204983994 base_test2 77.96448766974669"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-04T05:32:37.711990Z",
     "start_time": "2019-03-04T05:32:37.658021Z"
    }
   },
   "source": [
    "`cv2.HISTCMP_CORRE` 和 `cv2.HISTCMP_INTERSECT` 是"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[直方图 API](https://docs.opencv.org/3.1.0/d6/dc7/group__imgproc__hist.html#ga41a249ba9a536bf2b47e95f8c7dd42b0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更多资料\n",
    "[本节资料] (https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_histograms/py_histogram_equalization/py_histogram_equalization.html#histogram-equalization)\n",
    "[Cambridge in Color website] (https://www.cambridgeincolour.com/tutorials/histograms1.htm)\n",
    "\n",
    "[维基百科直方图均衡化] (https://zh.wikipedia.org/wiki/%E7%9B%B4%E6%96%B9%E5%9B%BE%E5%9D%87%E8%A1%A1%E5%8C%96#%E5%BD%A9%E8%89%B2%E5%9B%BE%E5%83%8F%E7%9B%B4%E6%96%B9%E5%9B%BE%E5%9D%87%E8%A1%A1%E5%8C%96)\n",
    "\n",
    "[How can I adjust contrast in OpenCV in C?\n",
    "] (https://stackoverflow.com/questions/10549245/how-can-i-adjust-contrast-in-opencv-in-c)\n",
    "- 直方图处理\n",
    "- 阈值化处理\n",
    "- 其他"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 反向投影"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 理论知识\n",
    "反向投影可以用来做图像分割，寻找感兴趣区间。\n",
    "- 反向投影是一种记录给定图像中的像素点如何适应直方图模型像素分布的方式。\n",
    "- 简单的讲， 所谓反向投影就是首先计算某一特征的直方图模型，然后使用模型去寻找图像中存在的该特征。\n",
    "- 例如， 你有一个肤色直方图 ( Hue-Saturation 直方图 ),你可以用它来寻找图像中的肤色区域:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-07T09:05:24.831299Z",
     "start_time": "2019-03-07T09:05:22.630509Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def nothing(x):\n",
    "    pass\n",
    "\n",
    "\n",
    "img = cv2.imread(\"./sample_img/back.jpg\")\n",
    "hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "hue = np.zeros(hsv.shape, dtype=np.uint8)\n",
    "\n",
    "\n",
    "cv2.createTrackbar(\"bins\", \"dst\", 0, 255, nothing)\n",
    "\n",
    "while(1):\n",
    "    bins = cv2.getTrackbarPos(\"bins\", \"dst\")\n",
    "    hue = cv2.mixChannels(hsv, hue, [0, 0])\n",
    "    hist = cv2.calcHist(hue, [0], None, [180], [0, 180])\n",
    "    hist = cv2.normalize(hist, hist, 0, 1, cv2.NORM_MINMAX, -1)\n",
    "\n",
    "    dst = cv2.calcBackProject([hsv], [0], hist, [0, 180], 1)\n",
    "\n",
    "    cv2.imshow(\"dst\", dst)\n",
    "\n",
    "    k = cv2.waitKey(1) & 0xff\n",
    "    if k == 27:\n",
    "        break\n",
    "\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-07T09:06:08.335388Z",
     "start_time": "2019-03-07T09:05:55.193401Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "def calc_backproject():\n",
    "    sample = cv2.imread(\"./sample_img/sample.png\")\n",
    "    target = cv2.imread(\"./sample_img/target.png\")\n",
    "\n",
    "    roi_hsv = cv2.cvtColor(sample, cv2.COLOR_BGR2HSV)\n",
    "    target_hsv = cv2.cvtColor(target, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "    cv2.imshow(\"sample\", sample)\n",
    "    cv2.imshow(\"target\", target)\n",
    "\n",
    "    roiHist = cv2.calcHist(roi_hsv, [0, 1], None,\n",
    "                           [30, 30], [0, 180, 0, 256])\n",
    "    cv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)\n",
    "    dst = cv2.calcBackProject([target_hsv], [0, 1],\n",
    "                              roiHist, [0, 180, 0, 256], 1)\n",
    "    cv2.imshow(\"dst\", dst)\n",
    "    plt.imshow(dst)\n",
    "\n",
    "calc_backproject()\n",
    "\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0vfpx8blzj207i06kt8x.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 模板匹配\n",
    "#### 理论\n",
    "学习目标\n",
    "- 查找图像中的指定对象\n",
    "- cv2.matchTemplate(), cv2.minMaxLoc()\n",
    "\n",
    "在一副图像中查找与模板图像最匹配（相似）的部分。对模板图像进行滑动匹配源图像\n",
    "\n",
    "`matchTemplate(image, templ, method[, result[, mask]]) -> result`\n",
    "- image: 待搜索图像， 8 位或者 32 位浮点型图像      大小： W×H\n",
    "- templ: 搜索模板，需要和原图像有一样的数据类型，且大小不能超过原图像 大小： w×h\n",
    "- method: 匹配方法\n",
    "    - M_SQDIFF = 0,   平方差匹配        数值越小，有着越高的匹配结果\n",
    "    - TM_SQDIFF_NORMED = 1, 归一化 平方差匹配    数值越小，有着越高的匹配结果\n",
    "    - 以下方法，数值越小，匹配结果越好\n",
    "    - TM_CCORR = 2, 相关匹配\n",
    "    - TM_CCORR_NORMED = 3, 归一化相关匹配\n",
    "    - TM_CCOEFF = 4, 系数匹配\n",
    "    - TM_CCOEFF_NORMED = 5  归一化相关系数匹配\n",
    "- result: 输出图像 大小 (W-w+1×H-h+1)\n",
    "[模板匹配方法](https://docs.opencv.org/3.4/df/dfb/group__imgproc__object.html)\n",
    "\n",
    "**简单法：平方差方法，速度快，但不是很精确\n",
    "复杂法：相关系数法，计算量大，较精确\n",
    "综合考虑选择运用哪种匹配方法**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`minMaxLoc(src[, mask]) -> minVal, maxVal, minLoc, maxLoc`\n",
    "- 函数功能：找到数组或者图像最小最大值及其位置\n",
    "- src: 要查找的数组\n",
    "- minVal, maxVal: 最小，最大值\n",
    "- minLoc, maxLoc; 最小，最大值的位置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-05T12:58:37.138072Z",
     "start_time": "2019-03-05T12:58:37.130079Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n",
      "(0.0, 24.0, (0, 0), (4, 4))\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "img = np.array(np.arange(25)).reshape(5, 5)\n",
    "print(img, cv2.minMaxLoc(img), sep='\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> eval() 用法说明"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-05T12:51:19.879502Z",
     "start_time": "2019-03-05T12:51:18.989974Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',\n",
    "           'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']\n",
    "\n",
    "for method in methods:\n",
    "    print(eval(method)) # 可以判断 methods 里面的值在 OpenCV 中对应的值\n",
    "\n",
    "    # 运行结果\n",
    "'''\n",
    "4\n",
    "5\n",
    "2\n",
    "3\n",
    "0\n",
    "1\n",
    "'''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 例程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-05T13:49:47.025583Z",
     "start_time": "2019-03-05T13:49:39.012189Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "img = cv2.imread('./sample_img/template (1).jpg', 0)\n",
    "img = cv2.resize(img, (600, 600))\n",
    "img2 = img.copy()\n",
    "template = cv2.imread('./sample_img/template (2).jpg', 0)\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "# All the 6 methods for comparison in a list\n",
    "methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',\n",
    "           'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']\n",
    "\n",
    "for meth in methods:\n",
    "    img = img2.copy()\n",
    "    method = eval(meth) # 可以判断 methods 里面的值在 OpenCV 中对应的值\n",
    "\n",
    "    # Apply template Matching\n",
    "    res = cv2.matchTemplate(img, template, method)\n",
    "\n",
    "    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n",
    "    #print(res)\n",
    "    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\n",
    "    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:\n",
    "        top_left = min_loc\n",
    "    else:\n",
    "        top_left = max_loc\n",
    "    bottom_right = (top_left[0] + w, top_left[1] + h)\n",
    "\n",
    "    cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2)\n",
    "\n",
    "    #cv2.imshow('Matching Result'+str(meth), res)\n",
    "\n",
    "    cv2.imshow('Detected Point'+str(meth), img)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`cv2.TM_CCORR` 方法的效果不是很好\n",
    "\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0s8u3msbkj211y0lcdty.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 多目标匹配"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### cv2.TM_CCOEFF_NORMED 方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T03:09:04.712912Z",
     "start_time": "2019-03-06T03:08:59.682803Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time: 0.07096028327941895\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import time\n",
    "\n",
    "t0 = time.time()\n",
    "img = cv2.imread(\"./sample_img/mario.jpg\")\n",
    "template = img[170:220, 334:373, :]\n",
    "img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) # 用归一化的方法，阈值的设定比较方便\n",
    "threshold = 0.8 # 表示模板和检测目标 80% 的匹配程度就认为是所要查找的目标\n",
    "loc = np.where(res >= threshold)\n",
    "for pt in zip(*loc[::-1]):\n",
    "    cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)\n",
    "\n",
    "print(\"time:\", time.time()-t0)\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0swcg57hzj20or0hrak2.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T03:06:19.051155Z",
     "start_time": "2019-03-06T03:06:18.708353Z"
    }
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "plt.hist(res.ravel());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0sw5kokwrj20b306aaa2.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### cv2.TM_SQDIFF_NORMED 方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T06:30:52.483586Z",
     "start_time": "2019-03-06T06:30:50.885503Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time: 0.09594225883483887\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import time\n",
    "\n",
    "t0 = time.time()\n",
    "img = cv2.imread(\"./sample_img/mario.jpg\")\n",
    "template = img[170:220, 334:373, :]\n",
    "img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "res = cv2.matchTemplate(img_gray, template, cv2.TM_SQDIFF_NORMED) # 在\n",
    "threshold = 0.2 # 表示模板和检测目标 80% 的匹配程度就认为是所要查找的目标\n",
    "loc = np.where(res <= threshold)\n",
    "for pt in zip(*loc[::-1]):\n",
    "    cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)\n",
    "\n",
    "print(\"time:\", time.time()-t0)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0swcw8cmdj20or0hrthu.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0sw60pzo5j20at06hwei.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### cv2.TM_CCORR_NORMED 方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T06:30:40.862266Z",
     "start_time": "2019-03-06T06:30:39.181231Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time: 0.05097007751464844\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import time\n",
    "\n",
    "t0 = time.time()\n",
    "img = cv2.imread(\"./sample_img/mario.jpg\")\n",
    "template = img[170:220, 334:373, :]\n",
    "img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "res = cv2.matchTemplate(img_gray, template, cv2.TM_CCORR_NORMED) # 在\n",
    "threshold = 0.95 # 表示模板和检测目标 80% 的匹配程度就认为是所要查找的目标\n",
    "loc = np.where(res >= threshold)\n",
    "for pt in zip(*loc[::-1]):\n",
    "    cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)\n",
    "\n",
    "print(\"time:\", time.time()-t0)\n",
    "\n",
    "cv2.imshow(\"img\", img)\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**此方法把一个不是很明显的目标也检测出来，此方法的性能估计比较高**\n",
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0swdp2xh9j20or0hrajz.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T03:07:34.751633Z",
     "start_time": "2019-03-06T03:07:34.386845Z"
    }
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "plt.hist(res.ravel());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://ws1.sinaimg.cn/large/acbcfa39ly1g0swe959nkj20a6066mx6.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Tips"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T02:31:35.571156Z",
     "start_time": "2019-03-06T02:31:35.564161Z"
    }
   },
   "outputs": [],
   "source": [
    "a = [1, 2, 3, 4]\n",
    "a[::-1] # 反转\n",
    "#结果  [4, 3, 2, 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Python zip 功能说明](http://www.runoob.com/python/python-func-zip.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-06T02:52:52.287138Z",
     "start_time": "2019-03-06T02:52:52.276144Z"
    }
   },
   "outputs": [],
   "source": [
    "a = [1, 2, 3]\n",
    "b = [4, 5, 6]\n",
    "c = [4, 5, 6, 7, 8]\n",
    "zipped = zip(a, b)     # 打包为元组的列表\n",
    "\n",
    "[k for k in zip(*zipped)]          # 与 zip 相反，*zipped 可理解为解压，返回二维矩阵式\n",
    "# 结果 [(1, 2, 3), (4, 5, 6)]"
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "284.306px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
